import numpy as np
import pd as pd

# 读入数据
df = pd.read_csv("D:/python/Lab1/Last.csv")

# value_counts()函数获取每案件原因出现的频次
df_1 = df.案件原因.value_counts()
# print(df_1)

# 如遇中文显示问题可加入以下代码
from pylab import mpl
mpl.rcParams['font.sans-serif'] = ['SimHei']  # 指定默认字体
mpl.rcParams['axes.unicode_minus'] = False  # 解决保存图像是负号'-'显示为方块的问题

# 扇形图显示“案件原因”的占比
# df.案件原因.value_counts().plot(kind='pie')
# plt.show()

# 将数据转换为时间序列数据，调用pandas的to_datetime函数
df['start_time'] = pd.to_datetime(df['start_time'])

from datetime import timedelta, datetime
s_date = datetime(2004, 2, 9)  # 起始时间
e_date = datetime(2018, 5, 4)  # 结束时间
start_time = pd.date_range(s_date, e_date)  # 范围

# 生成一个分组桶，以每1个月作为一个组，按照date对数据进行标记
bins = pd.date_range(s_date, e_date + timedelta(days=1), freq='M')
labels = [f'Month{i + 1}' for i in range(len(bins) - 1)]
df['Month_group'] = pd.cut(df['start_time'], bins=bins, right=False, labels=labels)
# print(df['Month_group'])

# 按案件原因划分数据集
list1 = []
for i in df.groupby(['案件原因', 'Month_group']):
    list1.append(i)
df = np.array(list1, dtype=object)
# print(df)

import pandas as pd
from sklearn.tree import DecisionTreeClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score

# 读入数据集
data = pd.read_csv("D:/python/Lab1/Last.csv")

# 筛选出有关案件原因占比的特征
# X = data[['省', '市', '上述经历', '案件基本情况']]
X = data[['省', '市', '区', 'start_time']]
y = data['案件原因']

# 将特征值数值化（需要先对分类特征进行编码）
X = pd.get_dummies(X)

# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3)

# 定义决策树分类器，并进行训练
clf = DecisionTreeClassifier()
clf.fit(X_train, y_train)

# 进行预测并计算准确率
y_predict = clf.predict(X_test)
accuracy = accuracy_score(y_test, y_predict)
print("Accuracy: ", accuracy)
